<template>
    <div>
        <Modal v-model="showModal"
            :title="`${typeName}详情`"
            width="1000"
            :mask-closable = "false"
            footer-hide
            @on-cancel="hide">
            <Row class="targetHeader" style="margin-bottom: 10px;">
                <Select filterable v-model="query.targetName" :placeholder="`请选择${typeName}`" @on-change="getTargetInfo(1)"
                    style="width:180px; margin-right: 15px;" transfer clearable>
                    <Option v-for="item in targetTeamData" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
                </Select>
                <Select filterable v-model="query.status" placeholder="请选择解决状态"  style="width: 150px;margin-right:15px;" @on-change="getTargetInfo(1)" clearable>
                    <Option :value="1">未解决</Option>
                    <Option :value="6">已解决</Option>
                </Select>
                <Page :total="teamInfoTotal"
                    show-total show-elevator
                    @on-change="getTargetInfo" style="float: right">
                </Page>
            </Row>
            <Table :columns="teamInfoCol" :data="teamInfoData"></Table>
        </Modal>
        <Modal v-model="reportGradeModal.show"
            :title="reportGradeModal.title"
            :mask-closable="false"
            :loading="reportGradeModal.loading"
            @on-ok="reportGrade('gradeValidate')"
            @on-cancel="handleReset('gradeValidate')"
            width="400px">
            <Form ref="gradeValidate" :model="gradeValidate" :rules="ruleChalValidate" :label-width="80">
                <Alert type="warning" show-icon v-if="applyCount > 0">申请过{{applyCount}}次提示，本次打分最多不允许超过{{curTarget.computeScore}}分</Alert>
                <FormItem label="评分" prop="score">
                    <InputNumber type="textarea" v-model="gradeValidate.score" :min="1" :max="curTarget.computeScore" :placeholder="'输入1~'+curTarget.computeScore+'的数字'" style="width:200px"></InputNumber>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>
import { queryTargetAllot, getTargetTeamList_new, reportGrade, getUserApplyTipRecord } from '@/api/drill_compete'

export default {
    props: {
        type: {
            type: Number,
            default: 0
        },
        stMode: {
            type: Number,
            default: 1
        },
        wpUpMode: {
            type: Number,
            default: 1
        },
        ctfDeduction: {
            type: Number,
            default: 20
        }
    },
    components: {
       
    },
    mounted() {
        this.getTargetTeamList()
    },
    data() {
        const validateScore = (rule,value,callback) => {
            let score = this.curTarget.computeScore;
            if((value && (value > score || value < 1)) || value === 0){
                callback(new Error(`请输入1~${score}的数字`));
            }else{
                callback()
            }
        }

        return {
            applyCount: 0,
            showModal: false,
            currentTargetId: '',
            query: {
                pageIndex: 1,
                pageSize: 10,
                teamId: '',
                sceneId: this.$route.query.id,
                targetName: '',
                status: 0
            },
            reportGradeModal:{
                show:false,
                title:'评分',
                loading:true
            },
            targetTeamData: [],
            teamInfoData: [],
            teamInfoTotal: 0,
            teamInfoCol:[
                {
                    title:`题目名称`,
                    key:'targetName',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    width:100,
                    placement:'top-left'
                },
                {
                    title:`题目镜像`,
                    key:'imageName',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    width:100,
                },
                {
                    title:'解决状态',
                    key:'status',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    render:(h,params)=>{
                        return h('Tag',{
                            props:{
                                color:this.handlerStatus(params.row.status).color
                            }
                        },this.handlerStatus(params.row.status).txt)
                    }
                },
                {
                    title:'分值',
                    key:'score',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    width:60
                },
                {
                    title:'IP',
                    key:'ip',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    width:100
                },
                {
                    title:'端口',
                    key:'port',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    width:60
                },
                {
                    title:'得分',
                    key:'grade',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    width:60,
                    render:(h,params)=>{
                        return h('span', params.row.grade ? params.row.grade : 0)
                    }
                },
                {
                    title:'操作',
                    align:'center',
                    width:200,
                    placement:'top-right',
                    action:true,
                    render:(h,params)=>{
                        return h('div',[
                            h('Button',{
                                props:{
                                    type:'primary',
                                    size:'small',
                                    disabled: this.wpUpMode === 1
                                                // 针对竞赛提交，提交flag类型、隐藏中的、分值为0、未上传报告的题目禁止打分
                                                ? params.row.isNeedSubmitFlag==='1' || params.row.visibility === 0 || params.row.score === 0 || !this.hasReport
                                                // 针对题目提交，提交flag类型、隐藏中的、分值为0、未上传报告的题目禁止打分
                                                : params.row.isNeedSubmitFlag==='1' || params.row.visibility === 0 || params.row.score === 0 || !params.row.report 
                                },
                                style:{
                                    marginRight:'5px',
                                    width:'60px'
                                },
                                on:{
                                    click: async()=>{
                                        this.gradeValidate.questionId = params.row.id;
                                        this.gradeValidate.teamId = params.row.teamId;
                                        this.gradeValidate.score = params.row.grade || 0;
                                        await this.getUserApplyTipRecord(params.row.score, params.row.questionId).then(([length, computeScore]) => {
                                            this.computeScore = computeScore
                                            this.applyCount = length
                                        })
                                        this.curTarget = Object.assign(params.row, {
                                            computeScore: this.computeScore
                                        });
                                        this.reportGradeModal.show = true;
                                    }
                                }
                            },'评分'),
                        ])
                    }
                }
            ],
            gradeValidate:{
                "questionId": "",
                "sceneId": this.$route.query.id,
                "score": 0,
                "teamId": ""
            },
            curTarget: {},
            ruleChalValidate:{
                chaId:[
                    { required: true, message: `请选择题目`, trigger: 'change' },
                ],
                flag:[
                    { required: true, message: '请输入Flag', trigger: 'change' },
                ],
                score:[
                    { required: true, type:'number',message: '请输入分数', trigger: 'change' },
                    { validator: validateScore, trigger: 'change' }
                ],
            },
            hasReport: false,
            teamName:''
        }
    },
    computed: {
        typeName() {
            return this.type === 7 ? '任务' : '题目'
        }
    },
    methods: {
        getUserApplyTipRecord(score, questionId) {
            return new Promise(resolve => {
                getUserApplyTipRecord({
                    pageIndex: 1,
                    pageSize: 2147483646,
                    sceneId: this.$route.query.id,
                    teamId: this.currentTargetId
                }).then(({ code, data = {} }) => {
                    let computeScore = 0
                    let length = 0
                    if (code === 1) {
                        let items = data.items || []
                        let list = items.filter(item => item.questionId === questionId)
                        let filterLength = list.filter(item=> item.teamName == this.teamName) // 过滤团队名称一样的
                        length = filterLength.length
                        if (length) {
                            // 计算应该要扣除的分数
                            let deductionScore = this.ctfDeduction * length
                            if (deductionScore > 100) { // 扣分比例已经超过100，无法打分了
                                computeScore = 0
                            } else {
                                computeScore = Math.round(score * (100 - deductionScore) / 100)
                            }
                        } else {
                            computeScore = score
                        }
                    } else {
                        computeScore = score
                    }
                    resolve([length, computeScore])
                }).catch(() => {
                    computeScore = score
                    resolve([0, computeScore])
                })
            })
        },
        reportGrade(){
            this.$refs.gradeValidate.validate((valid) => {
                if(valid){
                    reportGrade(this.gradeValidate).then(data => {
                        if(data.code == 1){
                            this.reportGradeModal.show = false;
                            this.$Message.info('操作成功');
                            this.getTargetInfo();
                        }else{
                            this.reportGradeModal.loading = false;
                            setTimeout(()=>{
                                this.reportGradeModal.loading = true;
                            },500)
                            this.$Message.warning(data.message);
                        }
                    }).catch(error => {
                        this.reportGradeModal.loading = false;
                        setTimeout(()=>{
                            this.reportGradeModal.loading = true;
                        },500)
                    })
                }else{
                    this.reportGradeModal.loading = false;
                    setTimeout(()=>{
                        this.reportGradeModal.loading = true;
                    },500)
                }
            }).catch(() => {
                this.reportGradeModal.loading = false;
                setTimeout(()=>{
                    this.reportGradeModal.loading = true;
                },500)
            })
        },
        handleReset (name) {
            this.$refs[name].resetFields();
        },
        handlerStatus(status){
            const mapColor = {
                1:'red',
                6:'green'
            };
            const mapTxt = {
                1:'未解决',
                6:'已解决'
            }
            return{
                color:mapColor[status],
                txt:mapTxt[status]
            }
        },
        show (teamId, hasReport, teamName) {
            this.teamName = teamName
            this.hasReport = hasReport ? true : false // 需要转为boolean类型
            this.showModal = true;
            this.currentTargetId = teamId;
            this.query={
                pageIndex:1,
                pageSize:10,
                teamId:'',
                sceneId:this.$route.query.id,
                targetName:'',
                status:0
            };
            this.getTargetInfo();
        },
        hide() {
            this.$emit('hide')
        },
        getTargetInfo(pageIndex){
            if (pageIndex) {
                this.query.pageIndex = pageIndex
            }
            let params = {...this.query};
            params.teamId = this.currentTargetId;
            if(params.status===0){
                delete params.status;
            }
            if (this.stMode !== 1) {
                params.sortBy = 'sequence'
            }
            queryTargetAllot(params).then(res=>{
                if(res.code === 1){
                    this.teamInfoData = res.data.items;
                    this.teamInfoTotal = res.data.total;
                }else{
                    this.$Message.error(res.message)
                }
            })
        },
        getTargetTeamList(){
            getTargetTeamList_new({
                pageIndex:1,
                pageSize:2147483647,
                sceneId:this.$route.query.id,
                projectId:this.$route.query.prjid
            }).then(data => {
                if(data.code==1){
                    this.targetTeamData = data.data.items || data.data;
                }
            })
        },
    }
}
</script>
